// pages/gongyiguanli/index.js
const db = wx.cloud.database();
const {
  uploadImage,
  formatTime
} = require('../../utils/index')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      title: "",
      content: "",
      imagePath: ""
    },
    error: '',
    loading: false,
    image: {},
    checked: false,
    count: 0,
    rules: [{
        name: 'title',
        rules: {
          required: true,
          message: '必填标题'
        }
      },
      {
        name: 'content',
        rules: {
          required: true,
          message: '必填正文内容'
        }
      }
    ]
  },

  async checkedUpload(e) {
    let check = false
    const {
      value
    } = e.detail
    if (value) {
      const {
        filePath,
        fileId
      } = await uploadImage('dongtai')
      if (fileId) {
        check = true
      }
      this.setData({
        "image.imagePath": filePath,
        "formData.imagePath": fileId,
        checked: check
      })
    } else {
      this.setData({
        image: {},
        checked: check
      })
    }
  },

  formInputChange(e) {
    const {
      field
    } = e.currentTarget.dataset
    let c = this.data.formData.content.length
    if (field == 'content') {
      c = e.detail.value.length
    }
    this.setData({
      [`formData.${field}`]: e.detail.value,
      count: c
    })
  },
  submitForm() {
    this.selectComponent('#form').validate((valid, errors) => {
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })
        }
      } else {
        const params = {
          title: this.data.formData.title,
          content: this.data.formData.content,
          imagePath: this.data.formData.imagePath,
          create_at: new Date(),
          create_time: formatTime(new Date())
        }
        this.submit(params)
      }
    })
  },

  submit(params) {
    this.setData({
      loading: true
    })
    db.collection("dongtai").add({
      data: params
    }).then(res => {
      console.log(res);
      this.setData({
        loading: false
      })
      wx.navigateTo({
        url: '/pages/success/index?url=dongtaiguanli',
      })
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})